import { usePublicHooks } from "../../hooks";
import { usePublicFormats } from "../../formats";

import { reactive, onMounted, h, toRaw } from "vue";
import { delay } from "@pureadmin/utils";
import {
  WorkOrderList,
  WorkOrderAdd,
  WorkOrderUpdate,
  WorkOrderReply
} from "@/api/work_order";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import editForm from "../form.vue";
import replyForm from "../reply.vue";
import type { FormItemProps } from "./types";
import { useUserStoreHook } from "@/store/modules/user";
export function workOrderConfig() {
  const form = reactive({
    parking_lot_name: "",
    car_number: "",
    status: -1,
    page: 1,
    limit: 20
  });

  //从父级钩子里取东西
  const { pagination, loadingConfig, dataList, formRef, loading } =
    usePublicHooks();

  const { orderStatusShow, orderTypeShow } = usePublicFormats();

  const columns: TableColumnList = [
    {
      label: "停车场名称",
      prop: "park_name",
      width: 200
    },
    {
      label: "车牌号",
      prop: "car_number",
      width: 100
    },
    {
      label: "问题",
      prop: "question",
      width: 200
    },
    {
      label: "状态",
      prop: "status",
      width: 100,
      cellRenderer: ({ row }) => {
        let statusShow = "";
        let statusColor = "";
        if (row.status == 0) {
          statusShow = "待处理";
          statusColor = "red";
        } else if (row.status == 1) {
          statusShow = "已处理";
          statusColor = "green";
        }
        return h("span", { style: { color: statusColor } }, statusShow);
      }
    },
    {
      label: "照片",
      slot: "image",
    },
    {
      label: "反馈时间",
      prop: "created_at",
      width: 150
    },
    {
      label: "处理结果",
      prop: "answer",
      width: 140
    },
    {
      label: "处理时间",
      width: 150,
      cellRenderer: ({ row }) => {
        if (row.status == 1) {
          let handleAt = row.handle_at;
          return h("span", { style: { handleAt } }, handleAt);
        }
      }
    },
    {
      label: "备注",
      prop: "remark",
      width: 100
    },
    {
      label: "操作",
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    const { data } = await WorkOrderList(toRaw(form));
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  //页面加载
  onMounted(() => {
    onSearch();
  });

  //页面条数变化
  function onSizeChange(val) {
    form.limit = val;
    onSearch();
  }

  //页码变化
  function onCurrentChange(val) {
    loadingConfig.text = `正在加载第${val}页...`;
    loading.value = true;
    delay(600).then(() => {
      form.page = val;
      onSearch();

      //刷新数据
      loading.value = false;
    });
  }

  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}配置`,
      props: {
        formInline: {
          id: row?.id ?? "",
          park_name: row?.park_name ?? "",
          car_number: row?.car_number ?? "",
          image_new: "",
          question: row?.question ?? ""
        }
      },
      width: "40%",
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您新增了一条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              WorkOrderAdd(curData).then(res => {
                if (res.success) {
                  message(`操作成功`, {
                    type: "success"
                  });
                  chores();
                } else {
                  message(res.message, { type: "error" });
                }
              });
            } else {
              WorkOrderUpdate(curData).then(() => {
                // 实际开发先调用新增接口，再进行下面操作
                chores();
              });
            }
          }
        });
      }
    });
  }

  function openDialogReply(title = "新增", row?: FormItemProps) {
    addDialog({
      width: "30%",
      title: `${title}配置`,
      contentRenderer: () => h(replyForm, { ref: formRef }),
      props: {
        formInline: {
          id: row?.id ?? "",
          answer: row?.answer ?? "",
          remark: row?.remark ?? ""
        }
      },
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您新增了一条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "回复") {
              WorkOrderReply(curData).then(() => {
                // 实际开发先调用新增接口，再进行下面操作
                chores();
              });
            }
          }
        });
      }
    });
  }

  let roles = useUserStoreHook().username;

  return {
    roles,
    columns,
    form,
    loading,
    onSearch,
    resetForm,
    dataList,
    pagination,
    onSizeChange,
    onCurrentChange,
    loadingConfig,
    openDialog,
    openDialogReply
  };
}
